﻿var CreatedOKLodop7766=null;
var head = document.head || document.getElementsByTagName("head")[0] || document.documentElement;
var oscript = document.createElement("script");
oscript.src ="http://localhost:8000/CLodopfuncs.js?priority=1";
head.insertBefore( oscript,head.firstChild );
//引用双端口(8000和18000）避免其中某个被占用：
oscript = document.createElement("script");
oscript.src ="http://localhost:18000/CLodopfuncs.js?priority=0";
head.insertBefore( oscript,head.firstChild );
var barCodeType = "";
var customerId = "";
function getLodop(strTaskName){
    var defaultPrinter = null;
	var LODOP = getCLodopA();
	LODOP.PRINT_INIT(strTaskName);
	LODOP.SET_PRINT_STYLE("Bold",1);
	LODOP.SET_SHOW_MODE("NP_NO_RESULT",1);
	LODOP.SET_SHOW_MODE("HIDE_SBUTTIN_PREVIEW",1);
	LODOP.SET_SHOW_MODE("HIDE_QBUTTIN_PREVIEW",1);
	LODOP.SET_SHOW_MODE("PREVIEW_NO_MINIMIZE",1);
	LODOP.SET_PRINT_MODE("AUTO_CLOSE_PREWINDOW",1);
	LODOP.SET_PREVIEW_WINDOW(2,0,1,760,540,strTaskName+".打印");

    var printCount = LODOP.GET_PRINTER_COUNT();
    var selectPrinter = null;
    var localPrinterList = {};
    if(null == defaultPrinter){
        $.ajax({
            url : "../defaultPrinter/getPrinter",
            type : 'POST',
            async : false,
            data : {barCodeType:barCodeType,customerId:customerId},
            dataType : 'text',
            success : function(result) {
            	result = eval(result);
            	if(result.indexOf('_:_') > -1){
					selectPrinter = result;
				}else{
                    defaultPrinter = result;
                }
            }
        });
	}
	var index = -1;
    for(var i=0;i<printCount;i++){
        var curLocalPrinter = LODOP.GET_PRINTER_NAME(i+":DriverName");
        localPrinterList[curLocalPrinter] = curLocalPrinter;
        if(defaultPrinter == curLocalPrinter){
        	index = i;
        	break;
		}
	}
	if(index == -1){
    	if(null != selectPrinter){
            var values = selectPrinter.split("_:_")[0].split(",");
            var names = selectPrinter.split("_:_")[1].split(",");
            var html= "<select id='selectDefaultPrinter'>";
            for(var i=0;i<values.length;i++){
                html += "<option value='"+values[i]+"' "+(localPrinterList[values[i]] ? 'selected' : '')+">"+names[i]+"</option>";
            }
            html += "</select>";
            layui.use(['form'], function(){
                var layer = layui.layer;
                layer.open({
                    type: 1,
                    title: '选择打印机',
                    shadeClose: true,
                    skin: 'layui-layer-lan',
                    content: html,
                    btn: ['确定']
                    ,yes: function(index, layero){
                        var printerNameSet = $("#selectDefaultPrinter",layero).val();
                        $.ajax({
                            type: 'POST',
                            url: "../defaultPrinter/setPrinter",
                            data: {"printerNameSet":printerNameSet,barCodeType:barCodeType,customerId:customerId},
                            success: function(result){
                            },
                            dataType: 'text'
                        });
                        layer.close(index);
                    }
                });
            });
		}else{
            alert("请添加条码打印机！");
        }
		return;
	}
    LODOP.SET_PRINTER_INDEX(index);
	return LODOP;
}

//设置默认打印机
function setDefaultPrinter(printerName){
    $.ajax({
        type: 'POST',
        url: "../defaultPrinter/setPrinter",
        data: {"printerNameSet":printerName},
        success: function(result){
        },
        dataType: 'text'
    });
}
//获取CLODOP
function getCLodopA(){
	var LODOP;
	try {
		try {
			LODOP = getCLodop();
		} catch (err) {};
		if (!LODOP && document.readyState !== "complete") {
			alert("C-Lodop没准备好，请稍后再试！");
			return;
		};
		if (typeof(LODOP) == 'undefined') { 
			installLodop("CLodop_Setup_for_Win32NT.exe");
		}
		return LODOP;
	} catch (err) {
		alert("getLodop出错:" + err);
	};
}

//下载安装CLodop
function installLodop(name){
	var pathWeb = window.location.pathname.substring(window.location.pathname.indexOf("/",0),window.location.pathname.indexOf("/",1)+1);
	var url = window.location.origin+pathWeb+"script/js/lodop/"+name;
	window.open(url);                 
}
var color_font = {},ELECTRICCURRENT_MAP = {};
function initData(){
    $.ajax({
        url : "../defaultPrinter/initData",
        type : 'POST',
        async : false,
        data : {},
        dataType : 'json',
        success : function(result) {
            var level_color = result.LEVEL_COLOR;
            var elec_value = result.ELEC_VALUE;
            for(var i=0;i<level_color.length;i++){
               if(typeof(color_font[level_color[i]['EMES_CUSTOMER_ID']]) == 'undefined'){
                   color_font[level_color[i]['EMES_CUSTOMER_ID']] = {};
               }
               color_font[level_color[i]['EMES_CUSTOMER_ID']][level_color[i]['LEVEL_NAME']] = level_color[i]['COLOR_NAME'];
            }

            for(var i=0;i<elec_value.length;i++){
                if(typeof(ELECTRICCURRENT_MAP[elec_value[i]['EMES_CUSTOMER_ID']]) == 'undefined'){
                    ELECTRICCURRENT_MAP[elec_value[i]['EMES_CUSTOMER_ID']] = {};
                }
                ELECTRICCURRENT_MAP[elec_value[i]['EMES_CUSTOMER_ID']][elec_value[i]['ELEC_NAME']] = elec_value[i]['VALUE_NAME'];
            }
        }
    });
}

$(function(){
    initData();
});
//公共打印方法
function commonPrint(res,data,printCode){
    if(printCode){
        barCodeType = data.TYPE;
        customerId = data.EMES_CUSTOMER_ID;
        var workshop = data.workshop ? data.workshop : '四厂';
        var zwdx_workshop = workshop.substr(0,1);
        var number_workshop = zwdxToNumber(zwdx_workshop);
        var LODOP = getLodop("");
        var list = res.body.rows;
        var baseData = res.body.baseData;
        var pageNum = res.body.pageNum;
        var EFFICIENCY_NUM = (data.EFFICIENCY+'').indexOf(".") > -1 ? data.EFFICIENCY.replace(".","") : data.EFFICIENCY;
        var EFFICIENCY_FONT = data.ELECTRICCURRENT == " " ? EFFICIENCY_NUM : data.ELECTRICCURRENT+(EFFICIENCY_NUM+"").substr(1);
        var datestr_ = baseData.DATESTR.replace(new RegExp("-","g"),".");
        //E40CA4ACAD21499FB0EA1E356A9A8654为尚德  2FDB190FABF74A2DBB62A874EA4AAFDF为晶科  4008B50926F6482084065A565C63A901 阿特斯
        // var color_font={
        //     'E40CA4ACAD21499FB0EA1E356A9A8654':{"A1":"深蓝 Dark blue","A2":"蓝色1 Blue1","A3":"淡蓝1 Light blue1","A4":"淡蓝2 Light blue2","A5":"","A6":""}
        //     ,'2FDB190FABF74A2DBB62A874EA4AAFDF':{"A1":"D1","A2":"D","A3":"M","A4":"L"}
        //     ,'74AB01A7372546CDB1803DDACB40E36A':{"A1":"D1","A2":"D","A3":"M","A4":"L"}
        //     ,'53D5E7DDD5DF4C768D6DE87640351FF4':{"A1":"D1","A2":"D","A3":"M","A4":"L","A5":"","A6":""}
        //     ,'4008B50926F6482084065A565C63A901':{"A1":"LB","A2":"MB","A3":"DB","A4":"L"}
        // };
        var m_num = 1;
        if(list[0].MNO && list[0].MNO.length >=2){
            m_num = list[0].MNO.substring(1,2);
        }
        // var ELECTRICCURRENT_MAP = {
        //     'E40CA4ACAD21499FB0EA1E356A9A8654':{"A":"1","B":"2"}
        //     ,'2FDB190FABF74A2DBB62A874EA4AAFDF':{"H":"1","L":"2"}
        //     ,'74AB01A7372546CDB1803DDACB40E36A':{"H":"1","L":"2"}
        //     ,'53D5E7DDD5DF4C768D6DE87640351FF4':{"H":"1","L":"2"}
        //     ,'4008B50926F6482084065A565C63A901':{"H":"1","L":"2"}
        // };
        var replaceData = {"{细栅}":data.DS,"{机台号}":list[0].MNO,"{机台数}":m_num,"{效率数}":EFFICIENCY_NUM,"{效率字}":EFFICIENCY_FONT,"{效率}":data.EFFICIENCY,"{电流}":data.ELECTRICCURRENT,"{电流字}":((data.ELECTRICCURRENT==" ")?"":"-"+data.ELECTRICCURRENT)
            ,"{电流值}":((data.ELECTRICCURRENT==" "||data.ELECTRICCURRENT=="")?"":"-"+ELECTRICCURRENT_MAP[customerId][data.ELECTRICCURRENT]),"{颜色}":data.COLOR,"{颜色字}":color_font[customerId][data.COLOR],"{日期}":baseData.DATESTR,"{日期.}":datestr_,"{时间}":baseData.TIMESTR,"{批次号}":list[0].LOTNO,"{数量}":list[0].QTY,"{功率}":data.COMPLEX
            ,"{规格}":baseData.SPEC,"{备注}":data.DESCRIPTION,"{效率2}":(!isNaN(data.EFFICIENCY)?data.EFFICIENCY+"%":data.EFFICIENCY)
            ,"{功率2}":(data.COMPLEX !== ' '?data.COMPLEX+"W":data.COMPLEX),"{网板}":data.WB,"{网板字}":numberToZWDX(data.WB.substr(0,1)),"{网板数}":data.WBS,"{等级}":(data.COLOR ? data.COLOR.substr(0,1) : '')
            ,"{大数量}":data.PCS_NUM_BOX,"{主栅}":data.ZSW,"{检验员}":data.CHECK_ID,"{车间}":workshop,"{车间大写}":zwdx_workshop,"{车间数字}":number_workshop,"{网板分段}":data.MAP3,"{网板值4}":data.MAP4,"{网板值5}":data.MAP5
            ,"{工艺实验}":data.GYSY,"{质检员}":data.QC,"{备注1}":data.REMARK1PRINT,"{备注2}":data.REMARK2};
        if(!(new RegExp("({.+})+").test(printCode))){
            eval(printCode);
        }else{
            var print_method = "";
            if(printCode.indexOf("LODOP.PREVIEW") > -1){
                print_method = "LODOP.PREVIEW();";
            }else if(printCode.indexOf("LODOP.PRINT_DESIGN") > -1){
                print_method = "LODOP.PRINT_DESIGN();";
            }else if(printCode.indexOf("LODOP.PRINT_SETUP") > -1){
                print_method = "LODOP.PRINT_SETUP();";
            }
            var print_pagesize = "";
            var pagesizeRegExp = new RegExp("LODOP.SET_PRINT_PAGESIZE(.+);");
            if(pagesizeRegExp.test(printCode)){
                print_pagesize = pagesizeRegExp.exec(printCode)[0];
                printCode = printCode.replace(pagesizeRegExp,"");
            }
            printCode = printCode.replace("LODOP.PRINT_INIT(\"\");","");
            printCode = printCode.replace(print_method,"");
            for(var key in replaceData){
                printCode = printCode.replace(new RegExp(key,'g'),replaceData[key]);
            }
            var scriptCode = "";
            for(var i=0;i<list.length;i=i+pageNum){
                if(i>0)LODOP.NEWPAGE();
                for(var k=0;k<pageNum;k++){
                    scriptCode = printCode.replace(new RegExp("{条码"+(k==0?'':(k+1))+"}",'g'),list[i+k].CODE);
                }
                eval(scriptCode);
            }
            if(print_pagesize){
                eval(print_pagesize);
            }else{
                LODOP.SET_PRINT_PAGESIZE(1,1010,650,"");
            }
            if(print_method){
                eval(print_method);
            }else{
                LODOP.PRINT();
            }
        }
    }
}
//阿拉伯数字转中文大写
function numberToZWDX(num){
    var DX=["零", "一", "二", "三", "四", "五", "六", "七", "八", "九","十"];
    if(num>=0 && num<=10){
        return DX[num];
    }
    return num;
}
//中文大写转阿拉伯数字
function zwdxToNumber(zwdx){
    var number={"零":0, "一":1, "二":2, "三":3, "四":4, "五":5, "六":6, "七":7, "八":8, "九":9,"十":10};
    if(number[zwdx]){
        return number[zwdx];
    }
    return zwdx;
}


